package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * nio 客户端
 * @author jack.wu
 * @version 1.0
 * @date 2020-05-14
 */
public class NioClient {

    public static void main(String[] args) throws IOException {

        // 创建一个SocketChannel
        SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        // 提供服务器的ip和port
        InetSocketAddress address = new InetSocketAddress("127.0.0.1",6666);

        // 连接是非阻塞式的
        if (!socketChannel.connect(address)){
            // 没有连接就等待连接成功
            while (!socketChannel.finishConnect()){
                System.out.println("连接中，客户端不会阻塞，可以做其他工作~~~~");
            }
        }

        // 连接成功发送数据
        String data = "{'name':'李四'}";
        ByteBuffer buffer = ByteBuffer.wrap(data.getBytes());
        socketChannel.write(buffer);
        System.in.read();
    }
}
